import { useMemo } from 'react'
import type {
  PickerValue,
  PickerValueExtend,
  PickerViewProps,
} from './type'

export function withCache<T>(generate: () => T): () => T {
  let cache: T | null = null
  return () => {
    if (cache === null) {
      cache = generate()
    }
    return cache
  }
}

export function generateColumnsExtend(rawColumns: PickerViewProps['columns'], val: PickerValue[]): PickerValueExtend {
  // 缓存无用 每次都重新创建闭包环境
  const columns = withCache(() => {
    const c = typeof rawColumns === 'function' ? rawColumns(val) : rawColumns
    return c.map((column) => column.map((item) => (
      typeof item === 'string'
        ? {
          label: item,
          value: item,
        }
        : item)))
  })
  const items = withCache(() => val.map((v, index) => {
    const column = columns()[index]
    if (!column) return null
    return column.find((item) => item.value === v) ?? null
  }))
  const extend = {
    get columns() {
      return columns()
    },
    get items() {
      return items()
    },
  }
  return extend
}

export function useColumnsExtend(rawColumns: PickerViewProps['columns'], value: PickerValue[]): ReturnType<typeof generateColumnsExtend> {
  return useMemo(
    () => generateColumnsExtend(rawColumns, value),
    [rawColumns, value],
  )
}
